//
//  VersionCheck.swift
//  33web
//
//  Created by 宋海胜 on 2020/12/4.
//

import UIKit
import RxSwift
import RxAlamofire
import HandyJSON

// 蒲公英版本检查
class VersionCheck: NSObject {
    
    class func hasUpdateVersion(_ currentVC: UIViewController, _ disposeBag: DisposeBag) {
        
        let showUpdateTipCount = UserDefaults.standard.value(forKey: "showUpdateTipCount") as? Int ?? 0
        if showUpdateTipCount >= kMaxShowUpdateTipCount {
            return
        }
        let infoDic = Bundle.main.infoDictionary
        let currentBulidVersion = infoDic!["CFBundleVersion"]
        //蒲公英的apikey，appkey
        let paramDic = ["_api_key":kPGYApiKey,"appKey":kPGYAppKey]
        self.loadUpdate(paramDic, disposeBag) { model in
            let currentBV = Int(currentBulidVersion as! String)!
            let pgyerBV = model.buildBuildVersion!
            if currentBV < pgyerBV {
                
                //如果当前手机安装app的bulid号<蒲公英上最新打包的bulid号，则提示更新
                var msg = ""
                if let des = model.buildUpdateDescription, des != "" {
                    msg = "检测到新版本(\(pgyerBV))，当前版本(\(currentBV))，是否更新？\n更新内容：\n\(des)"
                } else {
                    msg = "检测到新版本(\(pgyerBV))，当前版本(\(currentBV))，是否更新？"
                }
                let alert = UIAlertController(title: "提示", message: msg, preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "取消", style: .default, handler: nil)
                let okAction = UIAlertAction(title: "更新", style: .default) { (action) in
                    let url = URL(string: model.buildShortcutUrl!)
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                }
                alert.addAction(cancelAction)
                alert.addAction(okAction)
                currentVC.present(alert, animated: true, completion: nil)
                UserDefaults.standard.setValue(showUpdateTipCount + 1, forKey: "showUpdateTipCount")
            }
        }
    }
    
    class func loadUpdate(_ params: [String: String], _ disposeBag: DisposeBag, successClosure:@escaping(PgyerVersionModel)->Void) {
        
        let urlStr = "https://www.pgyer.com/apiv2/app/check"
        do {
            try
                requestJSON(.post, urlStr.asURL(), parameters: params)
//                .subscribe(onNext: { (response, json) in
//                    print(json)
//                }).disposed(by: disposeBag)
                .map({ (response, json) -> Any in
                    print("*********** requestStart ***********\nurl: \(urlStr)\nparams: \(params) \nresponse: \(json))\n*********** requestEnd ***********")
                    return json
                })
                .mapModel(type: BaseModel.self)
                .subscribe(onNext: { (model) in
                    successClosure(model.data!)
                }).disposed(by: disposeBag)
        } catch {
            print(error)
        }
    }
}
